import React, { useEffect, useState } from "react";
import { DownloadOutlined, FormOutlined } from "@ant-design/icons";
import { Table, Button, Popconfirm } from "antd";
import "./index.less";
import { useHistory } from "react-router-dom";
import callNet from "@/servers/callNet";

export default function TemplateConfiguration() {
  const history = useHistory();
  const [listData, setListData] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    getTemplateLit();
  }, []);

  const deleteRow = async ({ templateId }) => {
    const res = await callNet.delete(`/delete_templates/${templateId}`);
    getTemplateLit()
  };

  const renderActions = (_, record) => {
    return (
      <div className="table-actions">
        <a className="edit" onClick={() => edit(record)}>
          编辑
        </a>
        <Popconfirm
          title="确实删除改行?"
          description="确实删除该行?"
          onConfirm={() => deleteRow(record)}
          okText="是"
          cancelText="否"
        >
          <a className="delete">删除</a>
        </Popconfirm>
      </div>
    );
  };

  const edit = ({ templateId }) => {
    history.push(`/main/templateEdit?pageStatus=edit&templateId=${templateId}`);
  };

  const columns = [
    {
      title: "模板名称",
      dataIndex: "templateName",
      key: "templateName",
    },

    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },

    {
      title: "操作",
      dataIndex: "actions",
      key: "actions",
      render: renderActions,
    },
  ];

  const getTemplateLit = async () => {
    try {
      setLoading(true);
      const { temalateList } = await callNet.get("/temalateList");
      setListData(temalateList);
    } catch (err) {
    } finally {
      setLoading(false);
    }
  };

  const createTemplate = () => {
    history.push("/main/templateEdit");
  };
  return (
    <div className="page-container">
      <div className="table-header">
        <h1>模板配置</h1>
        <div className="actions">
          <Button
            type="primary"
            icon={<FormOutlined />}
            size="middle"
            onClick={createTemplate}
          >
            创建模板
          </Button>
        </div>
      </div>
      <Table
        dataSource={listData}
        columns={columns}
        rowKey={(e) => e.templateId}
        loading={loading}
      />
    </div>
  );
}
